/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.io.Util;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.hibernate.Transaction;

import com.mr.qa.GlobalConfigs;
import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.GlobalConfigs.UploadFileType;
import com.mr.qa.bo.Question;
import com.mr.qa.bo.QuestionCategory;
import com.mr.qa.dao.impl.QuestionCategoryDAO;
import com.mr.qa.dao.impl.QuestionDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.ResumeForm;
import com.mr.qa.util.HibernateSessionFactory;
import com.mr.qa.util.mail.Mail;
import com.mr.qa.util.mail.MailUtil;

public class ResumeAction extends BaseAction
{
    private static final Log log = LogFactory.getLog(ResumeAction.class);
    public ActionForward doAction(ActionMapping mapping, ActionForm form,
                    HttpServletRequest request, HttpServletResponse response) 
                    throws Exception
    {
        ActionForward af = null;
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
        UserSession us = null;
        ResumeForm resumeForm = (ResumeForm)form;
        //go back to question after upload
        String questionId = resumeForm.getQuestionId();
        //for combination of the uploaded file
        String questionCategoryId = resumeForm.getQuestionCategoryId();
        
        String path = mapping.findForward("success").getPath();
        path = path.replace("!?",""+questionId);
        af = new ActionForward(path);
        af.setRedirect(true);
        
        QuestionCategory category = this.getQuestionCategory(questionCategoryId);
        if(category == null)
            return af;    
        String userLoginName = "";
        String userEmail = "";
        us = UserSessionUtil.getUserSession(request);        
        if(us != null)
        {
            userLoginName = us.getLoginName();
        }
        userEmail = request.getParameter("contactEmail");//the user enter in the view question page
        FormFile file = resumeForm.getFile();
        String resumeName = "";
        if(file != null && file.getFileSize() > 0)
        {
            int fileSize = file.getFileSize();
            if(fileSize > UploadFileType.getMaxSize(UploadFileType.attachment))
            {
                errors.add("", new ActionMessage("resume.oversize"));
            }
            else
            {
                resumeName = file.getFileName();
                resumeName = URLDecoder.decode(resumeName,"UTF-8");
                String extName = resumeName.substring(resumeName.lastIndexOf(".")+1);
                if(!(".doc.rtf.pdf.txt".indexOf(extName.toLowerCase()) > 0))
                {
                    errors.add("", new ActionMessage("resume.filename.format.mismatch"));
                }
                else
                {
                    String concerns = resumeForm.getConcerns();
                    if(concerns == null)concerns = "";
                    if(concerns.length() > 0)
                    {
                        concerns = concerns.replace("\n", "<br>");
                    }
                    String mailTo = category.getAdCategoryContactMail();
                    QuestionDAO questionDAO = new QuestionDAO();
                    Question question = questionDAO.findById(Integer.valueOf(questionId));
                    if (question.getEmail() != null){
                    	mailTo += "," + question.getEmail();
                    }
                    boolean sendMailOk = sendResumeAsMail(file,URLDecoder.decode(resumeForm.getQuestionTitle(),"UTF-8"),
                    category.getName(),mailTo,userEmail,concerns);
                    sendMailOk = false;
                    //if(!sendMailOk)
                    if(true)
                    {
                        //String fileName = resumeName.substring(0,resumeName.lastIndexOf(".")-1);//xx.txt                        
                        resumeName = category.getName()+"-"+questionId+"-"+userLoginName+"-"+resumeName;
                        String phisicalFileDirStr = GlobalConfigs.WEB_PHISICAL_ROOT_LOCATION+"resume";
                        File phisicalFileDir = new File(phisicalFileDirStr);
                        if(!phisicalFileDir.exists())
                        {
                            phisicalFileDir.mkdir();
                        }
                        String phisicalFilePath = phisicalFileDirStr+File.separator+resumeName;
                        try
                        {
                            InputStream in = file.getInputStream();
                            OutputStream out = new FileOutputStream(phisicalFilePath);
                            Util.copyStream(in, out);
                            in.close();
                            out.close();
                        }
                        catch(Exception e)
                        {
                            errors.add("", new ActionMessage("resume.upload.failure"));
                            log.error("exception:"+e+" while uploading resume:"+resumeName+" for question:"+questionId);
                        }
                    }
                    else //send mail failure
                    {
                        errors.add("", new ActionMessage("sendpasswordmail.failure"));
                    }
                }
            }//end oversize
        }
        else
        {
            errors.add("", new ActionMessage("resume.required"));
        }
        if(errors.size() > 0)
        {
            saveErrors(request.getSession(), errors);
        }
        else
        {
            log.info("sucessfully uploading resume:"+resumeName+" for question:"+questionId);
            messages.add("", new ActionMessage("resume.upload.success"));
            saveMessages(request.getSession(), messages);
        }
        return af;
    }
    
    private QuestionCategory getQuestionCategory(String questionCategoryId)
    {
        Transaction tx = null;
        try
        {
            QuestionCategoryDAO categoryDAO = new QuestionCategoryDAO();
            tx = HibernateSessionFactory.getSession().beginTransaction();
            QuestionCategory category = categoryDAO.findById(new Integer(questionCategoryId));
            tx.commit();
            return category;
        }
        catch(Exception e)
        {
            log.warn("find category by id="+questionCategoryId);
        }
        finally
        {
            HibernateSessionFactory.closeSession();  
        }
        return null;
    }
    
    private boolean sendResumeAsMail(FormFile file,String jobTitle,
            String adQuestionCategoryName, String adQuestionCategoryMail,
            String userMail,String concerns)
    {
        boolean sendOk = true;
        try
        {
            if(adQuestionCategoryMail == null || adQuestionCategoryMail.trim().length() == 0)
                return false;
            Mail htmlMail = new Mail();
            htmlMail.setFrom("resume@mainframer.cn");
            htmlMail.setTo(adQuestionCategoryMail);
            //htmlMail.setCc("ytstcn@yahoo.com.cn");
            //htmlMail.setBcc("tao_shang@hotmail.com");
            htmlMail.setFormFile(file);
            //log.info("job title:"+jobTitle);
            htmlMail.setSubject("Apply for "+jobTitle + " of " + adQuestionCategoryName +" From www.mainframer.cn");
            htmlMail.setBody("The resume sent from www.mainframer.cn. Please don't reply." +
                    "<br>The applicant's mail is: "+userMail
                    +"<br>The applicant's concerns is: <br>"+concerns);
            MailUtil.sendServiceSimpleHtmlMail(htmlMail);//?
            log.info("send resume mail:"+file.getFileName()+" to "+adQuestionCategoryMail+" for applying for "+adQuestionCategoryName+"-"+jobTitle);
        }
        catch(QaException qe)
        {
            sendOk = false;
            log.error("send resume mail QaException:"+qe);
        }
        catch(Exception e)
        {
            sendOk = false;
            log.error("send resume mail Exception:"+e);
        }
        return sendOk;
    }
}
